package com.lottery.ruok.lottrey.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.lib.dialog.NetWaitDialog;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.LoginSuccess;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetGuestRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.SaveGuestRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetGuestResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.SaveGuestResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.ContactUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import utils.Utils;
/*
* 免费试玩
* */

public class DemoActivity extends BaseActivity implements TextWatcher{

    @BindView(R.id.choose)
    ImageView choose;
    @BindView(R.id.protocol)
    TextView protocol;
    @BindView(R.id.tips)
    LinearLayout tips;
    @BindView(R.id.help)
    TextView help;
    @BindView(R.id.test_account)
    TextView testAccount;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.start_paly)
    Button startPaly;

    private boolean tipChoose = true;
    private GetGuestResponse getGuestResponse;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        ButterKnife.bind(this);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        if(dm.heightPixels <= 1280) {
            LinearLayout adjusting = findViewById(R.id.adjusting);
            adjusting.setOrientation(LinearLayout.VERTICAL);
            protocol.setPadding(20,0,0,0);
        }

        EventBus.getDefault().register(this);

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    private void init() {
        password.addTextChangedListener(this);

        RetrofitBase.getRetrofit().create(GetGuestRequest.class).getResult()
                .compose(RxHelper.<GetGuestResponse>handleResult())
                .subscribe(new RxSubscribe<GetGuestResponse>(this) {
                    @Override
                    protected void _onNext(GetGuestResponse g) {
                        if(g != null){
                            getGuestResponse = g;

                            help.setText(getGuestResponse.getHelp());

                            if(getGuestResponse.getUser() != null) {
                                testAccount.setText(Html.fromHtml("<font color='#661dac'>试玩账号   </font>" + getGuestResponse.getUser().getUsername()));
                            }
                        }
                    }

                    @Override
                    protected boolean showDialog() {
                        return false;
                    }
                });
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        listenToChange();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LoginSuccess event) {
        finish();
    }

    @OnClick({R.id.protocol, R.id.tips})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.protocol:
                Intent intent = new Intent(DemoActivity.this, OpenAccountProtocolActivity.class);
                startActivity(intent);
                break;
            case R.id.tips:
                if(tipChoose){
                    tipChoose = false;

                    choose.setImageResource(R.mipmap.check_none);
                } else {
                    tipChoose = true;

                    choose.setImageResource(R.mipmap.check_ok);
                }

                listenToChange();
                break;
        }
    }

    private void listenToChange(){
        if (password.getText().length() == 0 || !tipChoose) {
//            startPaly.setBackgroundResource(R.drawable.bg_corners_grey);
            startPaly.setTextColor(Color.parseColor("#8539D1"));
            startPaly.setEnabled(false);
        } else {
//            startPaly.setBackgroundResource(R.drawable.bg_corners_yellow);
            startPaly.setTextColor(Color.parseColor("#ffffff"));
            startPaly.setEnabled(true);
        }
    }

    @OnClick({R.id.start_paly})
    public void onViewClicked1(View view) {
        switch (view.getId()) {
            case R.id.start_paly:
                //sendAnalyticMsg("lottery_" + LoginActivity.ANALYTIC_VERSION + "_me_setting_start_free_play");
                startPaly();
                break;
        }
    }

    private void startPaly(){//暂时没有验证码
        if(getGuestResponse != null && getGuestResponse.getUser() != null) {
            final NetWaitDialog netWaitDialog = new NetWaitDialog();//这个特殊情况，NetWaitDialog逻辑单独写出来
            netWaitDialog.show(this);
            RetrofitBase.getRetrofit().create(SaveGuestRequest.class).getResult(getGuestResponse.getUser().getUsername(),
                    password.getText().toString(),
                    null)
                    .compose(RxHelper.<SaveGuestResponse>handleResult())
                    .subscribe(new RxSubscribe<SaveGuestResponse>(this) {
                        @Override
                        protected void _onNext(SaveGuestResponse saveGuestResponse) {

                            if(saveGuestResponse != null && saveGuestResponse.getUser() != null){
                                UserInfo.setUsername(saveGuestResponse.getUser().getUsername());
                                UserInfo.setNickname(saveGuestResponse.getUser().getNickname());
                                UserInfo.setAccount(saveGuestResponse.getUser().getAccount());
                                UserInfo.setToken(saveGuestResponse.getUser().getToken());
                                UserInfo.setIsTest(saveGuestResponse.getUser().getIs_test());
                                UserInfo.setMobilePhone(saveGuestResponse.getUser().getMobile_phone());
                                UserInfo.setIsTry(0);
                                UserInfo.setUserId("");
                                EventBus.getDefault().post(new LoginSuccess());
                                ContactUtils.uploadContacts(DemoActivity.this);
                            }
                            netWaitDialog.dismissAllowingStateLoss();

//                            UserLoginTask.TaskListener listener = new UserLoginTask.TaskListener() {
//                                @Override
//                                public void onSuccess(RegistrationResponse registrationResponse, Context context) {
//                                    //After successful registration with Applozic server the callback will come here
//                                    EventBus.getDefault().post(new LoginSuccess());
//                                    netWaitDialog.dismissAllowingStateLoss();
//                                }
//
//                                @Override
//                                public void onFailure(RegistrationResponse registrationResponse, Exception exception) {
//                                    //If any failure in registration the callback  will come here
//                                    EventBus.getDefault().post(new LoginSuccess());
//                                    netWaitDialog.dismissAllowingStateLoss();
//                                }
//                            };
//                            User user = new User();
//                            user.setUserId(UserInfo.getUsername()); //userId it can be any unique user identifier
//                            user.setAuthenticationTypeId(User.AuthenticationType.CLIENT.getValue());
//                            user.setPassword(Utils.md5(UserInfo.getUsername()));
//                            new UserLoginTask(user, listener, DemoActivity.this).execute((Void) null);
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);

                            netWaitDialog.dismissAllowingStateLoss();
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        } else {
            Utils.showToast(Common.NO_NET);
        }
    }
}
